package update.links.com.versionupdate;

import android.support.annotation.NonNull;
import android.util.Log;

import com.prim.update.http.UpdateHttpClient;
import com.prim.update.UpdateManager;
import com.prim.update.callback.CommentCallback;
import com.prim.update.callback.DownloadCallback;
import com.prim.update.model.Progress;

import org.xutils.common.Callback;
import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.util.Map;

/**
 * ================================================
 * 作    者：linksus
 * 版    本：1.0
 * 创建日期：3/6 0006
 * 描    述：
 * 修订历史：
 * ================================================
 */
public class xUtilsClient implements UpdateHttpClient, Callback.ProgressCallback<File> {

    private Callback.Cancelable tempDoanloadTask;//当前下载任务，可取消的对象

    private DownloadCallback callback;

    private String tag;

    private String results;

    private static final String TAG = "xUtilsClient";

    private Progress progress;

    public xUtilsClient(String tag) {
        this.tag = tag;
    }

    @Override
    public void enqueueGet(@NonNull String url, final CommentCallback commentCallback) {
        Log.e(TAG, "enqueueGet: get请求");
        RequestParams params = new RequestParams(url);
        // 设置请求方式
        params.setMethod(HttpMethod.GET);
        params.setConnectTimeout(30000);

        x.http().get(params, new CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                results = result;
                Log.e(TAG, "onSuccess: " + result);
                commentCallback.onSuccess(result);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                results = null;
                Log.e(TAG, "onError: " + ex.getMessage());
                commentCallback.onError(ex.getMessage());
            }

            @Override
            public void onCancelled(CancelledException cex) {
                results = null;
                commentCallback.onCancelled();
            }

            @Override
            public void onFinished() {
                commentCallback.onFinished();
            }
        });
    }

    @Override
    public void enqueuePost(@NonNull String url, Map<String, String> params, CommentCallback commentCallback) {
        Log.e(TAG, "enqueuePost: post 请求");
        RequestParams requestParams = new RequestParams(url);
        if (params != null && !params.isEmpty()) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                requestParams.addQueryStringParameter(entry.getKey(), entry.getValue());
            }
        }
        // 设置请求方式
        requestParams.setMethod(HttpMethod.POST);
        requestParams.setConnectTimeout(30000);

        x.http().post(requestParams, new CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                results = result;
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                results = null;
                Log.e(TAG, "onError: " + ex.getMessage());
            }

            @Override
            public void onCancelled(CancelledException cex) {
                results = null;
            }

            @Override
            public void onFinished() {

            }
        });
    }

    @Override
    public void download(@NonNull String url, @NonNull String path, DownloadCallback callback) {
        this.callback = callback;
//        //在下载的时候判断是否存在文件
        File file = new File(path + ".tmp");
//        File file2 = new File(path);
//        Log.e(TAG, "download: " + file.exists());
//        if (file2.exists()) {
//            file2.delete();
//        }
        if (file.exists()) {
            file.delete();
        }
        RequestParams requestParams = new RequestParams(url);
        requestParams.setSaveFilePath(path);
        tempDoanloadTask = x.http().get(requestParams, this);
        //注意更新界面需要在UI线程中
    }

    @Override
    public void pauseDownload() {

    }

    @Override
    public void currentDownload() {

    }

    @Override
    public void cancleDownload() {
        if (tempDoanloadTask != null) {
            if (!tempDoanloadTask.isCancelled()) {
                tempDoanloadTask.cancel();
            }
        }
    }

    @Override
    public void onWaiting() {

    }

    @Override
    public void onStarted() {
        UpdateManager.getInstance().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                callback.onStart(tag);
            }
        });
    }

    @Override
    public void onLoading(long total, long current, boolean isDownloading) {
        if (progress == null) {
            progress = new Progress();
            progress.totalSize = total;
            progress.status = Progress.LOADING;
            progress.tag = tag;
        }
        Progress.changeDownloadProgress(progress, current, new Progress.Action() {
            @Override
            public void call(final Progress progress) {
                UpdateManager.getInstance().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        callback.onProgress(progress);
                    }
                });
            }
        });
    }

    @Override
    public void onSuccess(File result) {
        UpdateManager.getInstance().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                callback.onFinish(tag);
            }
        });
    }

    @Override
    public void onError(final Throwable ex, boolean isOnCallback) {
        UpdateManager.getInstance().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                callback.onError(ex.getMessage(), tag);
            }
        });
    }

    @Override
    public void onCancelled(CancelledException cex) {
        UpdateManager.getInstance().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                callback.onCancle(tag);
            }
        });
    }

    @Override
    public void onFinished() {
        UpdateManager.getInstance().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                callback.onFinish(tag);
            }
        });
    }
}
